package com.zh.tea.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.github.pagehelper.PageInfo;
import com.zh.tea.entity.Cart;
import com.zh.tea.entity.Tea;
import com.zh.tea.entity.Type;
import com.zh.tea.entity.User;
import com.zh.tea.service.CartService;
import com.zh.tea.service.TeaService;
import com.zh.tea.service.TypeService;
import com.zh.tea.service.UserService;
import com.zh.tea.service.impl.CartServiceImpl;
import com.zh.tea.service.impl.TeaServiceImpl;
import com.zh.tea.service.impl.TypeServiceImpl;
import com.zh.tea.service.impl.UserServiceImpl;

import net.sf.json.JSONObject;

/**
 * Servlet implementation class CartServlet
 */
@WebServlet("/CartServlet")
public class CartServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CartServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/html; charset=utf-8");
		PrintWriter out=response.getWriter();
		HttpSession session=request.getSession();
		CartService carts=new CartServiceImpl();
		String opt=request.getParameter("opt");
		if("sel".equals(opt)){
		//	Integer pagNo=Integer.parseInt(request.getParameter("pagNo"));
		//	Integer pagSize=Integer.parseInt(request.getParameter("pagSize"));
			if(session.getAttribute("typelist")==null){
				TypeService types=new TypeServiceImpl();
				List<Type> listtype=types.selectAllType();
				session.setAttribute("typelist", listtype);
			}
			
			
			User user=(User)session.getAttribute("User");
			Cart cart=new Cart();
			cart.setUserid(user.getId());
			PageInfo<Cart> page=carts.getCartByPage(cart, 1, 5);
			List<Map<String,String>> list=new ArrayList<>();
			for(Cart car:page.getList()){
				Map<String,String > map=new HashMap<>();
				TeaService teas=new TeaServiceImpl();
				Tea tea=teas.getTeaById(car.getTeaid());
				map.put("teaname", tea.getName());
				map.put("teaprice", tea.getPrice().toString());
				map.put("teaspec",tea.getSpec());
				map.put("teacount", car.getPrice().toString());
				map.put("teapic1", tea.getPic1());
				map.put("count", car.getCount().toString());
				list.add(map);
			}
			session.setAttribute("cartlist", list);
			response.sendRedirect("cart.jsp");
		}else if("del".equals(opt)){
			Integer cartid=Integer.parseInt(request.getParameter("cartid"));
			int n=carts.delCart(cartid);
			if(n>0){
				out.print("<script>alert('删除成功！')location.href='cart.jsp'</script>");
			}else{
				out.print("<script>alert('删除失败！')location.href='cart.jsp'</script>");
			}
		}else if("add".equals(opt)){
			User user=(User)session.getAttribute("User");
			Tea tea=(Tea)session.getAttribute("tea");
			
			Integer count=Integer.parseInt(request.getParameter("count"));
			Cart cart=new Cart();
			cart.setCount(count);
			cart.setTeaid(tea.getId());
			cart.setUserid(user.getId());
			cart.setPrice(tea.getPrice());
			int n=carts.addCart(cart);
			if(n>0){
				out.print("<script>alert('添加购物车成功！'); location.href='CartServlet?opt=sel'</script>");
			}
		}else if("showAll".equals(opt)){
			//检测session中有没有品牌和种类的值，如果没有重新查询
			TeaService teas=new TeaServiceImpl();
			UserService users=new UserServiceImpl();
			
			int currentNumber = Integer.parseInt(request.getParameter("page")==null?"1":request.getParameter("page"));//页码
	        String currentPage = request.getParameter("limit") == null ? "10" : request.getParameter("limit");//大小
			
	        PageInfo<Cart> cartt= carts.getCartByPage(null, currentNumber, Integer.parseInt(currentPage));
	        	List cartlist=new ArrayList<>();
	        	for(Cart cart:cartt.getList()){
	        		Map<String,Object> map=new HashMap();
	        		//将tea的对象转换成map
	        		 Class clazz = cart.getClass();
	        		 System.out.println(clazz);
	        	     Field[] fields = clazz.getDeclaredFields();
	        	     for (Field field : clazz.getDeclaredFields()) {
	        	      field.setAccessible(true);
	        	      String fieldName = field.getName();
	        	      Object value;
					try {
						value = field.get(cart);
						map.put(fieldName, value);
					} catch (IllegalArgumentException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IllegalAccessException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
	        	       
	        	    	}
	        	    //替换Map中的类型teaid
	        	     Tea listtea=teas.getTeaById(cart.getTeaid());
	        	     map.put("teaname", listtea.getName());
	        	     User user=users.selectOne(cart.getUserid());
	        	     map.put("username", user.getRealname());
	        	 cartlist.add(map);
	        	}
	        
	        

				JSONObject jsonObject = new JSONObject();
		        jsonObject.put("code", 0);
		        jsonObject.put("msg", "");
		        jsonObject.put("count", cartt.getTotal());
		        jsonObject.put("data", cartlist);
			
				String json=jsonObject.toString();
				out.print(json);
		}
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
